package com.baohulu.baohulu.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.baohulu.baohulu.R;
import com.baohulu.baohulu.base.BaseActivity;
import com.baohulu.baohulu.base.BaseResponseCallback;
import com.baohulu.baohulu.common.Const;
import com.baohulu.baohulu.utils.HttpUtil;
import com.baohulu.baohulu.utils.JsonUtil;
import com.baohulu.baohulu.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 扫码后的信息展示及开锁界面
 */
public class RentInfoActivity extends BaseActivity {
    private static final String TAG = "RentInfoActivity";

    @BindView(R.id.unlock)
    Button btnUnlock;
    @BindView(R.id.price)
    TextView tvPrice;
    @BindView(R.id.ball_img)
    ImageView ivBallImg;
    boolean isUnlockSuccess = false;
    Timer mTimer;
    int times = Const.LOOP_TIMES;
    private String ballKey = "";
    private double ballPrice = 0;
    private String eqKey = "";
    private int doorId = -1;
    private long startTime = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rent_info);
        ButterKnife.bind(this);
        ballKey = getIntent().getStringExtra(Const.Extra.BALL_KEY);
        eqKey = getIntent().getStringExtra(Const.Extra.EQ_KEY);
        doorId = getIntent().getIntExtra(Const.Extra.DOOR_INDEX, -1);
        mTimer = new Timer();
        getBallInfo(ballKey);
    }

    /**
     * 从服务器获取球的信息
     */
    private void getBallInfo(String ballKey) {
        JSONObject data = new JSONObject();
        try {
            data.put("key", ballKey);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String url = getString(R.string.url_base) + getString(R.string.url_get_ball_info);
        HttpUtil.post(this, url, data, new BaseResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog();
            }

            @Override
            public void onJsonObjectResponse(JSONObject jsonObject) {
                super.onJsonObjectResponse(jsonObject);
                try {
                    int state = jsonObject.getInt("state");
                    int type = jsonObject.getInt("ball_type");
                    ballPrice = jsonObject.getDouble("ball_price");
                    resolveBallInfo(state, type, ballPrice);
                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    hideProgressDialog();
                }

            }

            @Override
            public void onFailure(String msg) {
                hideProgressDialog();
                Log.e(TAG, "onFailure: " + msg);
                ToastUtil.showToast(msg);
            }

            @Override
            public void onCanceled() {
                super.onCanceled();
                hideProgressDialog();
                ToastUtil.showToast("请先登录！");
            }
        });

    }

    /**
     * 处理球信息响应结果
     *
     * @param state 球状态：1可用，0不可用
     * @param type  球的类型
     * @param price 球的价格
     */
    private void resolveBallInfo(int state, int type, double price) {
//        ToastUtil.showToast("resolveBallInfo: state=" + state + ",type=" + type + ",price=" + price);
        if (state == 0) {//不可用
            ToastUtil.showToast(R.string.ball_not_available);
            btnUnlock.setEnabled(false);
            btnUnlock.setBackground(getResources().getDrawable(R.drawable.bg_circle_green_unable));
        } else {
            String displayStr = "每小时" + price + "元";
            tvPrice.setText(displayStr);
            btnUnlock.setEnabled(true);
            btnUnlock.setBackground(getResources().getDrawable(R.drawable.selector_circle_btn));
        }
    }


    /**
     * 向服务器添加一条租借信息
     */
    @OnClick(R.id.unlock)
    public void addRentRecord() {
        final JSONObject data = new JsonUtil.JsonBuilder()
                .put("ball_key", ballKey)
                .put("eq_key", eqKey)
                .put("door_id", doorId)
                .build();

        String url = getString(R.string.url_base) + getString(R.string.url_add_rent_record);
        HttpUtil.post(this, url, data, new BaseResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog();
            }

            @Override
            public void onJsonObjectResponse(JSONObject jsonObject) {
                super.onJsonObjectResponse(jsonObject);
                try {
                    int state = jsonObject.getInt("state");
                    if (state == 1) {
                        Log.d(TAG, "添加租借记录成功！");
                        ToastUtil.showToast("添加租借记录成功！");
                        loopCheckUnlockState();
                    } else {
                        hideProgressDialog();
                        ToastUtil.showToast("租借失败,请重试！");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "addRentRecord: ", e);
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.showToast(msg);
                hideProgressDialog();
            }
        });
    }

    private void loopCheckUnlockState() {
        isUnlockSuccess = false;
        times = Const.LOOP_TIMES;
        mTimer.schedule(new CheckUnlockStateTask(), 0, 1000);
    }


    /**
     * 向服务端查询开锁状态
     */
    private void checkUnlockState() {
        final JSONObject data = new JsonUtil.JsonBuilder()
                .put("ball_key", ballKey)
                .put("eq_key", eqKey)
                .put("index", doorId)
                .build();

        String url = getString(R.string.url_base) + getString(R.string.url_check_unlock_state);
        HttpUtil.post(this, url, data, new BaseResponseCallback() {
            @Override
            public void onStart() {
                showProgressDialog();
            }

            @Override
            public void onJsonObjectResponse(JSONObject jsonObject) {
                super.onJsonObjectResponse(jsonObject);
                try {
                    int state = jsonObject.getInt("state");
                    if (state == 1 && !isUnlockSuccess) {//只处理第一次符合条件的响应
                        startTime = jsonObject.getLong("time");
                        isUnlockSuccess = true;
                        ToastUtil.showToast("租借成功！");
                        hideProgressDialog();
                    } else {//忽略其他响应
                        Log.d(TAG, "onJsonObjectResponse: ignore");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String msg) {
                ToastUtil.showToast(msg);
                hideProgressDialog();
            }
        });

    }

    @Override
    protected void onDestroy() {
        if (mTimer != null) {
            mTimer.cancel();
        }
        super.onDestroy();
    }

    public void onRentSuccess() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (startTime == 0) {
                    Log.e(TAG, "跳转计时界面出错：startTime = 0");
                    return;
                }
                goToTimerActivity();
            }
        });
    }

    /**
     * 跳转到计时页面
     */
    private void goToTimerActivity() {
        Intent intent = new Intent(this, TimerActivity.class);
        intent.putExtra(Const.Extra.START_TIME, startTime)
                .putExtra(Const.Extra.BALL_PRICE, ballPrice)
                .putExtra(Const.Extra.EQ_KEY, eqKey)
                .putExtra(Const.Extra.BALL_KEY, ballKey)
                .putExtra(Const.Extra.DOOR_INDEX, doorId);
        startActivity(intent);
        finish();
    }

    public void onLoopTimeOut() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                hideProgressDialog();
                ToastUtil.showToast("租借失败，请重试！");
            }
        });
    }

    class CheckUnlockStateTask extends TimerTask {
        @Override
        public void run() {
            if (!isUnlockSuccess && times > 0) {
                Log.d(TAG, "run: CheckingUnlockState " + (Const.LOOP_TIMES - times + 1) + " times");
                checkUnlockState();
                times--;
            } else {
                cancel();
                if (isUnlockSuccess) {
                    //租借成功，取消查询
                    Log.d(TAG, "Stop CheckingUnlockState: rent success!");
                    onRentSuccess();
                } else {
                    Log.d(TAG, "Stop CheckingUnlockState: timeout!");
                    onLoopTimeOut();
                }
            }
        }
    }
}
